//
//  HWGameCommunityAllListController.swift
//  HWanGame
//
//  Created by 王昌健 on 2022/10/24.
//  Copyright © 2022 94Wan. All rights reserved.
//

import UIKit
import JXSegmentedView
import IQKeyboardManagerSwift
class HWGameCommunityAllListController: HWBaseViewController {
    var isSheet = false
    var type = ""
    
    var backButton:UIButton!
    var searchBgView:UIView!
    var searchLogoImageView:UIImageView!
    var searchField:UITextField!
    var searchButton:UIButton!
    var keyword = ""
    
    var tableView:UITableView!
    var tableViewProtocol = HWGameCommunityAllListProtocol()
    var httpManager = HWGameCommunityHttpManager()
    var models:[HWGameCommunityAllListModel] = []
    var didClickItem:((_:HWGameCommunityAllListModel)->())?
    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        
        initFrame()
        
        addRefresh()
        
        loadData()
        
        addAction()
        
    }

}

extension HWGameCommunityAllListController {
    private func initUI() -> Void {
        IQKeyboardManager.shared.shouldResignOnTouchOutside = true
        IQKeyboardManager.shared.enableAutoToolbar = false
        
        navigationView.isHidden = true
        backButton = UIButton(type: .custom)
        backButton.setImage(UIImage(named: "navBackButton"), for: .normal)
        backButton.addTarget(self, action: #selector(backButtonClick(_:)), for: .touchUpInside)
        view.addSubview(backButton)
        
        searchBgView = UIView()
        if isSheet {
            searchBgView.frame = CGRect(x: 0, y: 0, width: 266*widthScale, height: 34*widthScale)
            backButton.isHidden = true
        } else {
            searchBgView.frame = CGRect(x: 0, y: 0, width: 248*widthScale, height: 34*widthScale)
            backButton.isHidden = false
        }
        
        searchBgView.backgroundColor = .white
        searchBgView.layer.shadowColor = UIColor.colorWithAlphaHexString(hexString: "#C4C4C4", alpha: 0.16).cgColor
        searchBgView.layer.shadowOffset = CGSize(width: 0, height: 0)
        searchBgView.layer.shadowRadius = 6*widthScale
        searchBgView.layer.shadowOpacity = 1
        searchBgView.layer.cornerRadius = 17*widthScale
        searchBgView.layer.borderWidth = 1
        searchBgView.layer.borderColor = UIColor.colorWithHexString(hexString: "#EEEEEE").cgColor
        view.addSubview(searchBgView)
        
        searchLogoImageView = UIImageView()
        searchLogoImageView.image = UIImage(named: "search");
        searchBgView.addSubview(searchLogoImageView)
        
        searchField = UITextField()
        searchField.font = UIFont.systemFont(ofSize: 14*widthScale)
        searchField.delegate = self
        searchField.returnKeyType = .search
        searchField.textColor = .colorWithHexString(hexString: "#333333")
        searchBgView.addSubview(searchField)
        
        let placeHoldLabel = UILabel.init()
        placeHoldLabel.text = "请输入游戏名称"
        placeHoldLabel.textColor = UIColor.colorWithHexString(hexString: "#888888")
        placeHoldLabel.font = UIFont.systemFont(ofSize: 14*widthScale)
        searchField.setValue(placeHoldLabel, forKey: "_placeholderLabel")
        searchField.addTarget(self, action: #selector(searchTextFieldChange(_:)), for: .editingChanged)
        
        let innerShadow = CALayer()
        innerShadow.frame = searchBgView.bounds
        
        let path = UIBezierPath(rect: innerShadow.bounds.insetBy(dx: -1,dy: -1))
        let cutout = UIBezierPath(rect: innerShadow.bounds).reversing()
        path.append(cutout)
        innerShadow.shadowPath = path.cgPath
        innerShadow.masksToBounds = true
        
        innerShadow.shadowColor = UIColor.colorWithAlphaHexString(hexString: "#989898", alpha: 0.5).cgColor
        innerShadow.shadowOffset = CGSize(width: 0,height: 0)
        innerShadow.shadowOpacity = 1
        innerShadow.shadowRadius = 4*widthScale
        innerShadow.cornerRadius = innerShadow.frame.size.height/2
        searchBgView.layer.addSublayer(innerShadow)
        
        searchButton = UIButton(type: .custom)
        searchButton.frame = CGRect(x: 0, y: 0, width: 54*widthScale, height: 28*widthScale)
        searchButton.layer.cornerRadius = 14*widthScale
        searchButton.titleLabel?.font = .boldSystemFont(ofSize: 13*widthScale)
        searchButton.setTitle("搜索", for: .normal)
        searchButton.layer.masksToBounds = true
        searchButton.addTarget(self, action: #selector(searchButtonClick(_:)), for: .touchUpInside)
        view.addSubview(searchButton)
        UIColor.gradientColor(view: searchButton, colors: [UIColor.colorWithHexString(hexString: "#FFB60A").cgColor,
                                                           UIColor.colorWithHexString(hexString: "#F66A05").cgColor], start: CGPoint(x: 0, y: 0), end: CGPoint(x: 1, y: 0))
        
        tableView = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        tableView.delegate = tableViewProtocol
        tableView.dataSource = tableViewProtocol
        tableView.backgroundColor = .colorWithHexString(hexString: "#FFFFFF")
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 40
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.showsVerticalScrollIndicator = false
        view.addSubview(tableView)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.ly_emptyView = LYEmptyView.empty(withImageStr: "", titleStr: "", detailStr: "暂无数据")
        tableView.ly_emptyView.contentViewOffset = -40
        if #available(iOS 15.0, *) {
            self.tableView.sectionHeaderTopPadding = 0
        } else {
            // Fallback on earlier versions
        }
    }
    
    private func initFrame() -> Void {
        
        backButton.snp.makeConstraints { make in
            make.left.equalTo(18*widthScale)
            make.top.equalTo(59*widthScale)
            make.width.height.equalTo(18*widthScale)
        }
        
        searchBgView.snp.makeConstraints { make in
            make.height.equalTo(34*widthScale)
            if isSheet {
                make.left.equalTo(18*widthScale)
                make.width.equalTo(266*widthScale)
                make.top.equalTo(5*widthScale)
            } else {
                make.left.equalTo(45*widthScale)
                make.width.equalTo(248*widthScale)
                make.top.equalTo(51*widthScale)
            }
        }
        
        searchLogoImageView.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(9*widthScale)
            make.width.height.equalTo(17*widthScale)
        }
        
        searchField.snp.makeConstraints { make in
            make.left.equalTo(searchLogoImageView.snp.right).offset(6*widthScale)
            make.height.equalTo(20*widthScale)
            make.centerY.equalToSuperview()
            make.right.equalTo(-10*widthScale)
        }
        
        searchButton.snp.makeConstraints { make in
            make.right.equalTo(-18*widthScale)
            make.width.equalTo(54*widthScale)
            make.height.equalTo(28*widthScale)
            make.centerY.equalTo(searchBgView)
        }
        
        tableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(searchBgView.snp.bottom).offset(9*widthScale)
        }
    }
}

extension HWGameCommunityAllListController:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}

extension HWGameCommunityAllListController {
    func loadData() -> Void {
        tableView.mj_footer?.isHidden = true
        
        print(type)
        
        httpManager.getGameCommunityAllList(type: type, keyword: keyword) { models in
            self.models.removeAll()
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            for m in models {
                self.models.append(m)
            }
            self.tableViewProtocol.models = self.models
            self.tableView.reloadData()
        } failure: { errorString in
            self.models.removeAll()
            self.tableViewProtocol.models = self.models
            self.tableView.reloadData()
            self.tableView.mj_footer?.isHidden = true
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        }

    }
    
    
    func addRefresh() -> () {
        
        tableView.mj_header = MJRefreshNormalHeader()
        tableView.mj_header?.setRefreshingTarget(self, refreshingAction: #selector(self.loadNewData))
        tableView.mj_footer = MJRefreshBackNormalFooter()
        tableView.mj_footer?.setRefreshingTarget(self, refreshingAction: #selector(self.loadMoreData))
        tableView.mj_footer?.isHidden = true
    }
    
    
    @objc func loadNewData() -> () {
        loadData()
    }
    
    @objc func loadMoreData() -> () {
        self.tableView.mj_footer?.endRefreshing()
        httpManager.getGameCommunityAllListFooter(type: type, keyword: keyword) { models in
            self.tableView.mj_footer?.endRefreshing()
            for m in models {
                self.models.append(m)
            }
            self.tableViewProtocol.models = self.models
            self.tableView.reloadData()
        } failure: { errorString in
            self.tableView.mj_footer?.endRefreshing()
        }
        
    }
}

extension HWGameCommunityAllListController:UITextFieldDelegate {
    @objc func searchTextFieldChange(_ textField:UITextField) ->Void {
        
        if textField.text?.count == 0 {
            keyword = ""
            loadData()
        } else {
            keyword = textField.text ?? ""
        }
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        textField.endEditing(true)
        keyword = textField.text ?? ""
        loadData()
        return true
    }
}

extension HWGameCommunityAllListController {
    func addAction() -> Void {
        self.tableViewProtocol.followButtonClick = {
            mod in
            self.httpManager.gameCommunityFollow(id: mod.id) { message in
                self.loadData()
            } failure: { errorString in
                self.view.showHUD(title: errorString)
            }

        }
        
        self.tableViewProtocol.didClickItem = {
            mod in
            let community = HWGameCommunityController()
            community.communityId = mod.id
            HWUniversal.getCurrentVc().navigationController?.pushViewController(community, animated: true)
            
            if self.isSheet == true {
                self.didClickItem?(mod)
            } else {
                
            }
        }
    }
    
    @objc func searchButtonClick(_:UIButton) -> Void {
        self.loadData()
        self.searchField.endEditing(true)
    }
    
    @objc func backButtonClick(_:UIButton) -> Void {
        self.navigationController?.popViewController(animated: true)
    }
}
